package jdbc.v1;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 数据源类：驱动，获取连接，关闭连接
 *
 * @author JoeZhou
 */
public class DataSource {

    private static String driver = "com.mysql.cj.jdbc.Driver";
    private String url = "jdbc:mysql://localhost:3306/j2102?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8";
    private String username = "joezhou";
    private String password = "joezhou";

    static {
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**\
     * 返回连接
     */
    public Connection getConnection() {
        Connection connection = null;
        try {
            // 创建一个连接
            connection = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    /**
     * 关闭连接
     */
    public void closeConnection(Connection connection) {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
